#include "atomic_0822_signal_preprocessing_service.h"


// 检查设备是否支持预处理
static bool isDeviceSupported(int device_id) {
    for (int i = 0; i < g_device_count; i++) {
        if (g_supported_devices[i] == device_id) {
            return 1;
        }
    }
    return 0;
}

// 添加支持的设备ID
static bool addSupportedDevice(int device_id) {
    // 检查是否已存在
    for (int i = 0; i < g_device_count; i++) {
        if (g_supported_devices[i] == device_id) {
            return 1; // 已存在，无需重复添加
        }
    }
    
    // 检查是否超过最大容量
    if (g_device_count >= 32) {
        return 0;
    }
    
    g_supported_devices[g_device_count++] = device_id;
    return 1;
}

// 滑动平均滤波实现
static double movingAverageFilter(double raw_val, double* history, int window_size, int index) {
    // 存储当前值到历史窗口
    history[index % window_size] = raw_val;
    
    // 计算平均值
    double sum = 0.0;
    for (int i = 0; i < window_size; i++) {
        sum += history[i];
    }
    return sum / window_size;
}

// 中值滤波实现
static double medianFilter(double raw_val, double* history, int window_size, int index) {
    // 存储当前值到历史窗口
    history[index % window_size] = raw_val;
    
    // 简单排序（冒泡排序）
    double sorted[window_size];
    for (int i = 0; i < window_size; i++) {
        sorted[i] = history[i];
    }
    
    for (int i = 0; i < window_size - 1; i++) {
        for (int j = 0; j < window_size - i - 1; j++) {
            if (sorted[j] > sorted[j + 1]) {
                // 交换元素
                double temp = sorted[j];
                sorted[j] = sorted[j + 1];
                sorted[j + 1] = temp;
            }
        }
    }
    
    // 返回中值
    return sorted[window_size / 2];
}

// 限幅滤波实现
static double clipFilter(double raw_val, double min_thresh, double max_thresh) {
    if (raw_val < min_thresh) {
        return min_thresh;
    } else if (raw_val > max_thresh) {
        return max_thresh;
    }
    return raw_val;
}

// 归一化处理实现
static double normalize(double raw_val, double min_thresh, double max_thresh) {
    if (max_thresh <= min_thresh) {
        return 0.0; // 避免除零错误
    }
    double clipped = clipFilter(raw_val, min_thresh, max_thresh);
    return (clipped - min_thresh) / (max_thresh - min_thresh);
}

// 预处理核心函数实现
int preprocessSignal(PreprocessInput* input, PreprocessOutput* output) {
    // 输入参数合法性检查
    if (input == nullptr || output == nullptr) {
        g_error_count++;
        return ATOMIC_SERVICE_NOT_SUPPORT;
    }
    
    // 检查设备是否支持
    if (!isDeviceSupported(input->device_id)) {
        g_error_count++;
        return ATOMIC_SERVICE_NOT_SEEK;
    }
    
    // 初始化输出结构体
    output->device_id = input->device_id;
    output->signal_type = input->signal_type;
    // 时间戳使用double类型（从uint64_t修改）
    output->timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
        std::chrono::system_clock::now().time_since_epoch()
    ).count();
    output->processed_val1 = 0.0;
    output->processed_val2 = 0.0;
    output->processed_val3 = 0.0;
    output->valid_count = 0;
    output->quality_score = 0;
    output->is_filtered = 0;
    output->return_type = ATOMIC_SERVICE_SUCCESS;
    
    // 检查输入数据有效性
    if (input->valid_count <= 0) {
        output->return_type = ATOMIC_SERVICE_NOT_READY;
        g_error_count++;
        return ATOMIC_SERVICE_NOT_READY;
    }
    
    // 历史数据缓存
    static double history_buf[8] = {0.0};
    static int history_index = 0;
    history_index = (history_index + 1) % 1000000; // 简单取模防止溢出
    
    // 根据算法类型处理数据
    switch (input->algo_type) {
        case ALGORITHM_NONE:
            // 不处理，直接复制原始数据
            output->processed_val1 = input->raw_val1;
            output->processed_val2 = input->raw_val2;
            output->processed_val3 = input->raw_val3;
            output->valid_count = input->valid_count;
            output->quality_score = 90;
            break;
            
        case ALGORITHM_MOVING_AVG: {
            // 滑动平均滤波
            int win_size = input->window_size;
            // 窗口大小校验
            if (win_size < 1) win_size = 3;
            if (win_size > 8) win_size = 8;
            
            output->processed_val1 = movingAverageFilter(input->raw_val1, history_buf, win_size, history_index);
            if (input->valid_count >= 2) {
                output->processed_val2 = movingAverageFilter(input->raw_val2, history_buf, win_size, history_index);
            }
            if (input->valid_count >= 3) {
                output->processed_val3 = movingAverageFilter(input->raw_val3, history_buf, win_size, history_index);
            }
            output->valid_count = input->valid_count;
            output->is_filtered = 1;
            output->quality_score = 85;
            break;
        }
            
        case ALGORITHM_MEDIAN: {
            // 中值滤波
            int win_size = input->window_size;
            if (win_size < 3) win_size = 3;
            if (win_size % 2 == 0) win_size++; // 确保奇数
            if (win_size > 8) win_size = 8;
            
            output->processed_val1 = medianFilter(input->raw_val1, history_buf, win_size, history_index);
            if (input->valid_count >= 2) {
                output->processed_val2 = medianFilter(input->raw_val2, history_buf, win_size, history_index);
            }
            if (input->valid_count >= 3) {
                output->processed_val3 = medianFilter(input->raw_val3, history_buf, win_size, history_index);
            }
            output->valid_count = input->valid_count;
            output->is_filtered = 1;
            output->quality_score = 80;
            break;
        }
            
        case ALGORITHM_CLIP:
            // 限幅滤波
            output->processed_val1 = clipFilter(input->raw_val1, input->min_threshold, input->max_threshold);
            if (input->valid_count >= 2) {
                output->processed_val2 = clipFilter(input->raw_val2, input->min_threshold, input->max_threshold);
            }
            if (input->valid_count >= 3) {
                output->processed_val3 = clipFilter(input->raw_val3, input->min_threshold, input->max_threshold);
            }
            output->valid_count = input->valid_count;
            output->is_filtered = 1;
            output->quality_score = 95;
            break;
            
        case ALGORITHM_NORMALIZE:
            // 归一化处理
            output->processed_val1 = normalize(input->raw_val1, input->min_threshold, input->max_threshold);
            if (input->valid_count >= 2) {
                output->processed_val2 = normalize(input->raw_val2, input->min_threshold, input->max_threshold);
            }
            if (input->valid_count >= 3) {
                output->processed_val3 = normalize(input->raw_val3, input->min_threshold, input->max_threshold);
            }
            output->valid_count = input->valid_count;
            output->is_filtered = 1;
            output->quality_score = 88;
            break;
            
        default:
            output->return_type = ATOMIC_SERVICE_NOT_SUPPORT;
            g_error_count++;
            return ATOMIC_SERVICE_NOT_SUPPORT;
    }
    
    // 更新全局统计
    g_total_processed++;
    return ATOMIC_SERVICE_SUCCESS;
}

// 获取服务状态
int getPreprocessStatus(PreprocessStatus* status) {
    if (status == nullptr) {
        g_error_count++;
        return ATOMIC_SERVICE_NOT_SUPPORT;
    }
    
    status->code = ATOMIC_SERVICE_SUCCESS;
    status->status = "Signal preprocessing service running";
    status->total_processed = g_total_processed;
    status->error_count = g_error_count;
    status->return_type = ATOMIC_SERVICE_SUCCESS;
    
    return ATOMIC_SERVICE_SUCCESS;
}

// 初始化支持的设备
static void initSupportedDevices() {
    if (g_device_count == 0) {
        addSupportedDevice(1001); // 温度传感器
        addSupportedDevice(1002); // 湿度传感器
        addSupportedDevice(1003); // 压力传感器
        addSupportedDevice(1004); // 振动传感器
    }
}

// 静态初始化
static bool g_initialized = [](){
    initSupportedDevices();
    return 1;
}();

// 回调函数实现
void preprocessSignal_func(PreprocessInput* request, PreprocessOutput* reply) {
    int ret = preprocessSignal(request, reply);
    reply->return_type = ret;
}